﻿<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title></title>
	<style type="text/css">
		body,h2
		{
			margin: 0px;
			padding: 0px;
		}
		#page
		{
			width: 810px;
			height: 620px;
			margin: 20px auto;
			text-align: center;
		}
		#mark
		{
			font-weight: 800;
		}
		#mark_con
		{ 
			color: red; 
		}
	</style>
</head>
<body>

	<div id="page">
		<h2>贪吃蛇游戏</h2>
        <div id="gameBox">
        	<canvas id="canvas" height="500" width="800" style="border:1px solid #66ff00;background: #9a968b"></canvas>
        </div>
        <div id="help">
            <div id="mark">得分：<span id="mark_con"></span></div>
        </div>
    </div>
    <script type="text/javascript">
 
    	var canvas=document.getElementById("canvas");	//获取到canvas对象
  		var ctx=canvas.getContext('2d');	//建立二维画布
  		var oMark = document.getElementById('mark_con');//分数显示框
    	var blocksize=20;//格子大小
    	var rows=canvas.height/blocksize; //行数
    	var cols=canvas.width/blocksize;//列数
    	var snakes=[] //用于存储蛇的位置
    	var foodX=20*blocksize;	//食物横坐标
    	var foodY=13*blocksize;	//食物的纵坐标
    	var initsnack=4;	//初始化蛇的长度
    	var direction=-1;//蛇初始方向为右边
    	var speed=1; //贪吃蛇移动的速率
    	function draw(){
    		//防止蛇移动的时候，画板上的数据没有清空
    		ctx.clearRect(0,0,blocksize * cols, blocksize * rows);
    		//画出横线
            for(var i=1;i<=rows;i++)
            {
            	ctx.beginPath();
            	ctx.moveTo(0,i*blocksize);
            	ctx.lineTo(cols*blocksize,i*blocksize);
            	ctx.strokeStyle="white";
            	ctx.closePath();
            	ctx.stroke();
            }
            //画出竖线
            for(var i=1;i<=cols;i++)
            {
            	ctx.beginPath();
            	ctx.moveTo(i*blocksize,0);
            	ctx.lineTo(i*blocksize,rows*blocksize);
            	ctx.strokeStyle="white";
            	ctx.closePath();
            	ctx.stroke();
            }
            //画蛇
            drawsnakes();
            //画出食物
            drawFood();
    	}
    	function drawsnakes(){
    		for(var i=0;i<snakes.length;i++)
            {
            	ctx.beginPath();
            	
            	ctx.moveTo(snakes[i].x,snakes[i].y);
            	ctx.lineTo(snakes[i].x+blocksize,snakes[i].y);
            	ctx.lineTo(snakes[i].x+blocksize,snakes[i].y+blocksize);
            	ctx.lineTo(snakes[i].x,snakes[i].y+blocksize);
            	if(i==0)
            	{
            		//蛇尾
            		ctx.fillStyle="#806464";
            		ctx.lineTo(snakes[i].x,snakes[i].y);
            	}
            	else if (i==snakes.length-1) {
            		//蛇头
            		ctx.fillStyle="#a24e33";
            	}
            	else
            	{
            		//蛇身体
            		ctx.fillStyle="#806464";
            	}
            	ctx.fillRect(snakes[i].x,snakes[i].y,blocksize,blocksize);
            	ctx.strokeStyle="gray";
            	ctx.stroke();
            	ctx.closePath();
            }
    	}
    	function drawFood(){
    		ctx.beginPath();
            ctx.fillStyle = "green";
            ctx.fillRect(foodX, foodY, blocksize, blocksize);
            ctx.moveTo(foodX, foodY);
            ctx.lineTo(foodX + blocksize, foodY);
            ctx.lineTo(foodX + blocksize, foodY + blocksize);
            ctx.lineTo(foodX, foodY + blocksize);
            ctx.lineTo(foodX, foodY);
            ctx.closePath();
            ctx.strokeStyle = "gray";
            ctx.stroke();
    	}
    	//随机产生一个食物
    	function addFood(){
        	foodX = Math.floor(Math.random() * (cols - 1)) * blocksize;
			foodY = Math.floor(Math.random() * (rows - 1)) * blocksize;
            //防止食物随机出现在蛇身上
            var temp=1;
       		for(var i=0;i<snakes.length;i++)
          	{
            	if(snakes[i].x==foodX&&snakes[i].y==foodY)
            	{
             		temp=0;
            		break;
          		}
         	}
      		if(temp==0)
        		addFood();
        }
    	function Cell(x,y){
    		this.x=x;
    		this.y=y;
    	}
    	//初始化
    	function init(){
    		for( var i = 0; i < initsnack; i++){
                snakes[i]=new Cell((i+1)*blocksize,60);
            }
            addFood();
            oMark.innerHTML = 0;
    	}
    	//1 左 -1 右 2 上 -2 下
    	function keydown(keyCode)
    	{
    		switch(keyCode)
    		{
    			case 37:
    				if(direction!=-1)	
    					direction=1;
    				break;
    			case 38:
    				if(direction!=-2)
    					direction=2;
    				break;
    			case 39:
    				if(direction!=1)
    					direction=-1;
    				break;
    			case 40:
    				if(direction!=2)
    					direction=-2;
    				break;
    		}
    		move();
    	}
    	//1 左 -1 右 2 上 -2 下
    	function move(){
    		var head=snakes[snakes.length-1];
    		switch(direction){
    			case 1://左
    				snakes.push(new Cell(head.x-blocksize,head.y));break;
    			case -1://右
    				snakes.push(new Cell(head.x+blocksize,head.y));break;
    			case 2:// 上
    				snakes.push(new Cell(head.x,head.y-blocksize));break;
    			case -2: //下
    				snakes.push(new Cell(head.x,head.y+blocksize));break;
    		}
            snakes.shift();
            IsEatFood();
            IsDie();
          	//console.log(snakes)
            draw();
    	}
    	//判断是否吃到了食物，即蛇头与食物坐标是否一致,若一致，则蛇长加一，重新生成新的食物,分数加1
    	function IsEatFood(){
    		var head=snakes[snakes.length-1];
    		if(head.x==foodX&&head.y==foodY)
    		{
    			oMark.innerHTML = (parseInt(oMark.innerHTML) + 1).toString();
    			addSnakes();
    			addFood();
    		}
    	}
    	function addSnakes(){
    		snakes.unshift(new Cell(blocksize*cols,blocksize * rows));
 
    	}
    	//判断是否死亡，要么蛇头超出边界，要么蛇头撞到蛇身体
    	function IsDie()
    	{
    		var head=snakes[snakes.length-1];
    		if(head.x==-blocksize||head.x==blocksize*cols||head.y==-blocksize||head.y==blocksize*rows)
    		{
    			alert("撞墙了,游戏结束！分数为:"+oMark.innerHTML);
    			clearInterval(interval);
    			window.location.reload();
    		}
    		else
    		{
    			var temp=1;
    			for (var i=0; i <snakes.length-2; i++) {
    				if (head.x==snakes[i].x&&head.y==snakes[i].y)
    				{
    					temp=0;
    					break;
    				}
    			}
    			if(temp==0)
    			{
    				alert("撞到身体了,游戏结束！分数为:"+oMark.innerHTML);
    				clearInterval(interval);
    				window.location.reload();
    			}
    		}
 
    	}	
    	// 启动函数
        window.onload = function(){
            
            init();
            draw();
        	interval = setInterval(move,200);
            document.onkeydown = function(event){
                var event = event || window.event;
                keydown(event.keyCode);
            }
        }
    </script>
</body>
</html>